#!/usr/bin/env python
# encoding: utf-8

Import('env')
Import('programs')


import os
import subprocess


def cmd_exists(cmd):
    return any(
        os.access(os.path.join(path, cmd), os.X_OK)
        for path in os.environ["PATH"].split(os.pathsep)
    )


def run_tests(target=None, source=None, env=None):
    names = ["pytest"]
    exes = [exe for exe in names if cmd_exists(exe)]
    if any(exes):
        name = exes[0]
        print('Found pytest as "{}"'.format(name))
        Exit(subprocess.call(name + ' -s -v -k "not slow"', shell=True))

    print('Unable to find pytest, tried these: ' + str(names))
    Exit(-1)


if 'test' in COMMAND_LINE_TARGETS:
    env.Alias('test',
        env.Depends(
            env.Command('run_tests', None, Action(run_tests, "Running tests")),
            programs
        )
    )
